/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.enduser.ui;

import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.FilterList;
import ca.odell.glazedlists.GlazedLists;
import ca.odell.glazedlists.TextFilterator;
import ca.odell.glazedlists.swing.TextComponentMatcherEditor;
import reportcenter.report.ui.AdminReportTable;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.view.ContextTreeView;
import org.springframework.binding.value.ValueModel;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.richclient.application.PageComponentContext;
import org.springframework.richclient.application.support.AbstractView;
import org.springframework.richclient.command.ActionCommand;
import org.springframework.richclient.command.ActionCommandExecutor;
import org.springframework.richclient.command.CommandGroup;
import org.springframework.richclient.command.GuardedActionCommandExecutor;
import org.springframework.richclient.command.support.AbstractActionCommandExecutor;
import org.springframework.richclient.command.support.GlobalCommandIds;
import org.springframework.richclient.list.ListSelectionValueModelAdapter;
import org.springframework.richclient.list.ListSingleSelectionGuard;
import reportcenter.report.business.AdminReportDao;
import reportcenter.datasource.business.DataSourceDao;
import reportcenter.report.dominio.report.Report;
import reportcenter.report.support.exporter.XlsExporterExecutor;
import reportcenter.report.ui.AdminReportView;
import reportcenter.support.threading.Job;
import reportcenter.support.threading.JobListener;
import reportcenter.support.threading.WorkerJob;
import spin.Spin;

/**
 *
 * @author renan_luz
 */
public class EndUserView extends AbstractView implements ApplicationListener,JobListener {

    private EndUserList userReportList;
    private AdminReportTable adminReportTable;
    private AdminReportDao adminReportDao;
    private DataSourceDao dataSourceDao;

    public DataSourceDao getDataSourceDao() {
        return dataSourceDao;
    }

    public void setDataSourceDao(DataSourceDao dataSourceDao) {
        this.dataSourceDao = dataSourceDao;
    }

    public AdminReportDao getAdminReportDao() {
        return adminReportDao;
    }

    public void setAdminReportDao(AdminReportDao adminReportDao) {
        this.adminReportDao = adminReportDao;
    }

    private JTextField filterField;
    @Override
    public JComponent createControl() {
        
        JPanel filterPanel = new JPanel(new BorderLayout());
            //Label do filtro
            JLabel filterLabel = getComponentFactory().createLabel("endUserFilter.label");
            filterPanel.add(filterLabel, BorderLayout.WEST);

            String tip = getMessage("endUserFilter.caption");
            filterField = getComponentFactory().createTextField();
            filterField.setToolTipText(tip);
            filterPanel.add(filterField, BorderLayout.CENTER);
            filterPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

            //instancia tabela de relatórios
            adminReportTable = new UserReportTableFactory().createAdminReportTable();

            JPanel view = new JPanel(new BorderLayout());
            JScrollPane sp = getComponentFactory().createScrollPane(adminReportTable.getControl());
            view.add(filterPanel, BorderLayout.NORTH);
            view.add(sp, BorderLayout.CENTER);

            return view;
//        return new ViewPanel();
    }
    
    private class UserReportTableFactory {

        public AdminReportTable createAdminReportTable() {
            AdminReportTable adminReportTable = new AdminReportTable(adminReportDao);

            adminReportTable.setDoubleClickHandler(exportToXlsExecutor);

            //Evento de filtro
            EventList baseList = adminReportTable.getBaseEventList();
//            TextFilterator filterator = GlazedLists.textFilterator(new String[]{"title", "subtitle", "query"});
            TextFilterator filterator = GlazedLists.textFilterator(new String[]{"title", "subtitle"});
            FilterList filterList = new FilterList(baseList, new TextComponentMatcherEditor(filterField, filterator));
            adminReportTable.setFinalEventList(filterList);

            //Configuração do menu de popup
            CommandGroup popup = new CommandGroup();

            CommandGroup exportGroup = new CommandGroup();
            exportGroup.setLabel("Exportar Relatório");
            exportGroup.add((ActionCommand) getWindowCommandManager().getCommand("exportToPdfCommand", ActionCommand.class));
            exportGroup.add((ActionCommand) getWindowCommandManager().getCommand("exportToXlsCommand", ActionCommand.class));
            exportGroup.add((ActionCommand) getWindowCommandManager().getCommand("exportToOdtCommand", ActionCommand.class));
            popup.add(exportGroup);
            //
            adminReportTable.setPopupCommandGroup(popup);

            adminReportTable.setStatusBar(getStatusBar());


            ValueModel selectionHolder = new ListSelectionValueModelAdapter(adminReportTable.getSelectionModel());
            new ListSingleSelectionGuard(selectionHolder, exportToPdfExecutor);
            new ListSingleSelectionGuard(selectionHolder, exportToXlsExecutor);
            new ListSingleSelectionGuard(selectionHolder, exportToOdtExecutor);


            return adminReportTable;
        }
    }
    
    private GuardedActionCommandExecutor exportToPdfExecutor = new ExportToPdfExecutor();

    private class ExportToPdfExecutor extends AbstractActionCommandExecutor {

        public void execute() {

            JOptionPane.showMessageDialog(null, "Exportação PDF: disponível em breve!");
        }
    }
    private GuardedActionCommandExecutor exportToXlsExecutor = new ExportToXlsExecutor();

    private class ExportToXlsExecutor extends AbstractActionCommandExecutor {

        public void execute() {
            
            final Report report = adminReportTable.getSelectedReport();
            WorkerJob job = (WorkerJob) Spin.off(new XlsExporterExecutor(report));

            // use the Spin.over functionality
            job.addJobListener((JobListener) Spin.over(EndUserView.this));

            // execute the job
            job.run();
        }
    }
    private GuardedActionCommandExecutor exportToOdtExecutor = new ExportToOdtExecutor();

    private class ExportToOdtExecutor extends AbstractActionCommandExecutor {

        public void execute() {
            JOptionPane.showMessageDialog(null, "Exportação ODT: disponível em breve!");
        }
    }
    
    private ActionCommandExecutor refreshExecutor = new RefreshExecutor();
    private class RefreshExecutor implements ActionCommandExecutor {

        public void execute() {
            adminReportTable.refreshTable();
        }
    }

    /**
     * Registra os executores de comando com os comandos associados a eles(comandos registrados em "richclient-application-context.xml"). 
     * Esse método é invocado pelo framework para tornar a view(ex: botão deletar) visível.
     */
    protected void registerLocalCommandExecutors(PageComponentContext context) {
        context.register("exportToPdfCommand", exportToPdfExecutor);
        context.register("exportToXlsCommand", exportToXlsExecutor);
        context.register("exportToOdtCommand", exportToOdtExecutor);
        context.register("refreshCommand", refreshExecutor);
    }

    
    public void start() {
        getStatusBar().setMessage("Iniciando processo de geração do relatório..."); // And/or other Swing stuff
        getStatusBar().getProgressMonitor().taskStarted("Inicializando", -1);
    }

    public void end() {
//        getStatusBar().setMessage("Geração de relatório finalizada!"); // And/or other Swing stuff
        getStatusBar().getProgressMonitor().done();
    }

    public void progress(int percent) {
//        getStatusBar().setMessage(percent + "% completo"); // And/or other Swing stuff
        getStatusBar().getProgressMonitor().worked(percent);
    }

    public void status(String msg) {
        getStatusBar().setMessage(msg);
    }
    

    public void onApplicationEvent(ApplicationEvent e) {
//        adminReportTable.onApplicationEvent(e);
    }
    
    
    
  public class ViewPanel extends javax.swing.JPanel implements ExplorerManager.Provider {  
     
       private ExplorerManager em;  
     
       private ViewPanel() {  
          setLayout(new BorderLayout());  
           em = new ExplorerManager();  
           em.setRootContext(EndUserNode.reports());  
           ContextTreeView view = new ContextTreeView();
//           ListView view = new ListView();
//           IconView view = new IconView();
           
           //view.setRootVisible(false);  
           add(view);  
       }  
     
       @Override  
       public ExplorerManager getExplorerManager() {  
          return em;  
       }  
     
   }  
}
